<?php

require_once APPPATH.'models/gnc_db_mysql'.EXT;

class M_keluar_masuk extends Gnc_db_mysql {
	protected $data_source	= 'lkm_t_log_km';

	public function is_student($nim) {
		$query = $this->db->query("SELECT * FROM aka_m_student WHERE `key`='$nim'");
		if ($query->num_rows() > 0) 
			return true;
		else
			return false;
	}

	public function is_data_exist($key_aka_student, $dt_log, $key_lkm_status) {
		$query = $this->db->query("SELECT * FROM lkm_t_log_km 
				WHERE key_aka_student='$key_aka_student'
					AND dt_log='$dt_log'
					AND key_lkm_status='$key_lkm_status'");
		if ($query->num_rows() > 0) 
			return true;
		else
			return false;

	}

	public function get_log_by_date($date) {
		$data = array();
		$query = $this->db->query("SELECT l.*, m.name FROM lkm_t_log_km as l, aka_m_student as m 
								WHERE l.key_aka_student=m.key 
									AND l.dt_log LIKE '$date%' 
									ORDER BY l.key_aka_student, l.dt_log ASC");
		
		foreach ($query->result_array() as $row)
		{
			
			$data[] = $row;
		}

		//echo count($data)."<br>";
		
		$data = $this->strip_data_from_duplicate($data);

		//echo count($data)."<br>";
		
		$data = $this->group_data_by_nim($data);

		//echo count($data)."<br>";

		$data = $this->resume_data_by_pair_outin($data);

		return $data; 
	}

	protected function strip_data_from_duplicate($data) {
		$tmp_data = array();
		
		$old_nim = "";
		$old_dt_log = "";
		$old_status = "";

		for($i=0;$i<count($data);$i++) {
			if($old_nim == $data[$i]['key_aka_student'] 
					&& $old_dt_log == $data[$i]['dt_log']
						&& $old_status == $data[$i]['key_lkm_status'] ) {

			}else{
				$tmp_data[] = $data[$i];
				$old_nim = $data[$i]['key_aka_student'];
				$old_dt_log = $data[$i]['dt_log'];
				$old_status = $data[$i]['key_lkm_status'];
			}
		}
		return $tmp_data;
	}

	protected function group_data_by_nim($data) {
		$tmp_data = array();
		for($i=0;$i<count($data);$i++) {
			$tmp_data[$data[$i]['key_aka_student']][] = $data[$i];
		}
		return $tmp_data;
	}

	protected function resume_data_by_pair_outin($data) {
		$tmp_data = array();
		foreach($data as $nim => $logs) {
			$tmp_data[$nim]['log'] = $logs;
			$resume_log = array();
			for($i=0; $i<count($logs); $i++) {
				if($logs[$i]['key_lkm_status'] == 'OUT') {
					if(!isset($resume_log[count($resume_log)]['OUT']) )
						$resume_log[count($resume_log)]['OUT'] = $logs[$i];
					else
						$resume_log[]['OUT'] = $logs[$i];
				}else{
					if(!isset($resume_log[count($resume_log)]['OUT']) ) {
						$set = false;
						for($j=0;$j<count($resume_log);$j++) {
							if(!isset($resume_log[$j]['IN']) ) {
								$resume_log[$j]['IN'] = $logs[$i];
								$set = true;
							}
						}
						if(!$set) $resume_log[]['IN'] = $logs[$i];
					}
				}
				$tmp_data[$nim]['resume'] = $resume_log;
			}
		}
		return $tmp_data;
	}
}

/* EOF modules/apl/models/m_test_1.php */